package com.kai;


import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Component
public class MailUtils {
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    /**
     * 发送邮件
     * @param subject
     * @param setTo
     * @param context
     * @param attachmentFilename
     * @param inputStream
     * @throws MessagingException
     */
    public void sendMail(String subject,
                            String setTo,
                            String context,
                            String attachmentFilename,
                            InputStream inputStream) throws MessagingException, IOException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        //邮件标题
        helper.setSubject(subject);
        //发送时间
        helper.setSentDate(new Date());
        //发送人
        helper.setFrom(username);
        //接收人
        helper.setTo(setTo);
        //邮件正文内容
        helper.setText(context);
        ByteArrayResource ar = new ByteArrayResource(IOUtils.toByteArray(inputStream));
        //附件内容
        // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
        helper.addAttachment(attachmentFilename,ar);
        javaMailSender.send(mimeMessage);
    }


    /**
     * 发送邮件
     * @param subject
     * @param setTo
     * @param context
     * @param attachmentFilename
     * @param file file文件
     * @throws MessagingException
     */
    public void sendMail(String subject,
                         String setTo,
                         String context,
                         String attachmentFilename,
                         File file) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        //邮件标题
        helper.setSubject(subject);
        //发送时间
        helper.setSentDate(new Date());
        //发送人
        helper.setFrom(username);
        //接收人
        helper.setTo(setTo);
        //邮件正文内容
        helper.setText(context);
        //附件内容
        // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
        helper.addAttachment(attachmentFilename,file);
        javaMailSender.send(mimeMessage);
    }
}
